<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 用户答题记录表（馆内形式答题）
 */

class AnswerActivityUserAnswerRecord extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'answer_activity_user_answer_record';



    /**
     * 判断此活动是否有人答过题
     */
    public function  isBeenAnswer($id)
    {
        return $this->where('act_id', $id)->first();
    }

    /**
     * 判断是否有人答过此题
     */
    public function  isBeenProblem($id)
    {
        return $this->where('problem_id', $id)->first();
    }

    /**
     * 写入馆内答题记录
     */
    public function addUserAnswerRecord($data, $unit_id, $user_guid, $answer_time)
    {

        $this->guid = get_guid();
        $this->act_id = $data[0]['act_id'];
        $this->user_guid = $user_guid;
        $this->unit_id = $unit_id ?: 0;
        $this->problem_id = $data[0]['id'];
        $this->status = 0;
        $this->times = $answer_time;
        $this->expire_time = date('Y-m-d H:i:s', strtotime("+" . $answer_time . " second"));
        $this->save();
        return $this->guid;
    }
    /**
     * 修改馆内答题记录
     * @param  $res 馆内答题记录对象
     */
    public function changeUserAnswerRecord($res, $answer_id, $content, $status)
    {
        $res->answer_id = $answer_id ?: 0;
        $res->answer = $content;
        $res->status = $status;
        $res->times = time() - strtotime($res->create_time);
        return $res->save();
    }

    /**
     * 根据guid，获取问题记录
     * @param guid
     */
    public function getAnswerRecordByGuid($guid)
    {
        $res = $this->where('guid', $guid)->first();
        return $res;
    }

    /**
     * 或者总答题时长
     * @param guid
     */
    public static function getAnswerTotalTimes($user_guid, $act_id,$unit_id = null)
    {
        $res = self::where('user_guid', $user_guid)
            ->where('act_id' , $act_id)
            ->where(function ($query) use ($unit_id) {
            if ($unit_id) {
                $query->where('unit_id', $unit_id);
            }
        })->sum('times');
        return $res;
    }

    /**
     * 获取用户回答的所有题
     * @param act_id 活动id
     * @param user_guid 用户guid
     * @param unit_id 单位id
     * @param status array 答题状态  0表示所有 1代表正确  2代表错误   3 超时回答（算错误）默认2
     */
    public function getHaveAnswer($act_id, $user_guid, $unit_id = null, $status = [])
    {
        $res = $this->where('act_id', $act_id)->where('user_guid', $user_guid)->where(function ($query) use ($unit_id, $status) {
            if ($unit_id) {
                $query->where('unit_id', $unit_id);
            }
            if ($status) {
                $query->whereIn('status', $status);
            }
        })->pluck('problem_id');

        return $res;
    }



    /**
     * 获取用户今日剩余答题机会
     * @param $user_guid   用户guid
     * @param $act_id   活动id
     * @param $answer_number  活动每次答题次数
     * @param $share_number   活动每次分享次数
     */
    public function surplusAnswerNumber($user_guid, $act_id, $number, $share_number)
    {
        $AnswerActivityUnitUserNumberModel = new AnswerActivityUnitUserNumber();
        $number_day = $AnswerActivityUnitUserNumberModel->getUnitAnswerNumber($user_guid, $act_id, 0, date('Y-m-d'));

        $number_day = $number_day ?: 0;
        $activityShareModel = new AnswerActivityShare();
        $today_share_number =  $activityShareModel->getUserShareNumber($act_id, $user_guid, date('Y-m-d')); //获取今日分享次数
        $today_share_number = $today_share_number ?: 0;

        $share_number = $share_number > $today_share_number ? $today_share_number : $share_number; //取小的数据次数

        return $number - $number_day + $share_number;
    }

    /**
     * 获取用户单位答题剩余答题次数
     * @param $act_id 活动id
     * @param $unit_id 图书馆id
     * @param $is_loop 是否可以循环，只对 场馆答题 有效    1可以   2 不可以
     * 
     * 馆内答题   答题进度：  1/5      爬楼梯：答题进度 52/100        轮次：已答轮次：5轮   
     */
    public function isHaveSurplusUnitAnswerNumber($user_guid, $act_id, $unit_id, $data)
    {
        if ($data['is_loop'] == 1) {
            return true; //无限次答题机会
        }

        //轮次，只限制每日答题次数
        //爬楼梯形式，不仅限制每日答题次数，还要限制每个馆总次数
        //馆内答题，不仅限制每日答题次数，还要限制每个馆总答题次数

        //获取用户今日答题次数
        //  $activityUnitUserNumberModel = new AnswerActivityUnitUserNumber();
        // $answer_number_day = $activityUnitUserNumberModel->getUnitAnswerNumber($user_guid, $act_id, null, date('Y-m-d'));
        // if (!empty($answer_number_day) && $answer_number_day >= $data['number']) {
        //     return false;
        // }

        $surplus_answer_number = $this->surplusAnswerNumber($user_guid, $act_id, $data['number'], $data['share_number']);
        if (empty($surplus_answer_number) || $surplus_answer_number <= 0) {
            return '今日答题次数已用完';
        }

        if ($data['pattern'] == 2) {
            return true; //轮次排名，不判断馆总次数
        }

        $activityUnitModel = new AnswerActivityUnit();
        $answer_number = $activityUnitModel->unitAnswerNumber($data['pattern'], $user_guid, $act_id, $unit_id);

        if ($data['pattern'] == 1 && $answer_number >= $data['answer_number']) {
            return '当前馆答题次数已答完，请重新选择'; //馆内答题，不仅限制每日答题次数，还要限制每个馆总答题次数
        }

        if ($data['pattern'] == 3 && $answer_number >= $data['total_floor']) {
            return '当前馆答题次数已答完，请重新选择'; //爬楼梯形式，不仅限制每日答题次数，还要限制每个馆总次数
        }

        return true;
    }

    /**
     * 用户参与人次、答题次数统计
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time 单位id 开始时间
     * @param end_time 单位id 结束时间
     * @param type 类型 1 参与人次  2 答题次数
     */
    public function partNumberStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null, $type = 1)
    {
        $res = $this->select('id', 'user_guid', 'act_id')->where(function ($query) use ($act_id, $unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        });

        if ($type == 1) {
            $res = $res->groupBy('user_guid');
        }
        $result = $res->get()->toArray();
        return count($result);
    }

    /**
     * 答题次数统计(折线图)
     * @param act_id 活动id
     * @param unit_id 单位id 数组形式
     * @param start_time  开始时间
     * @param end_time  结束时间
     * @param is_month  是否按月统计
     */
    public function partStatistics($act_id, $unit_id = null, $start_time = null, $end_time = null, $is_month = false)
    {
        if (empty($start_time)) {
            $start_time = date('Y-m-d 00:00:00');
            $end_time = date('Y-m-d H:i:s');
        }

        if ($is_month) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m') as dates"), DB::raw("count(id) as count")];
        } elseif (date('Y-m-d', strtotime($start_time)) == date('Y-m-d', strtotime($end_time))) {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d %H') as dates"), DB::raw("count(id) as count")];
        } else {
            $field = ['id', DB::raw("DATE_FORMAT(create_time,'%Y-%m-%d') as dates"), DB::raw("count(id) as count")];
        }
        $res = $this->select($field)->where(function ($query) use ($act_id, $unit_id, $start_time, $end_time) {
            if ($act_id) {
                $query->where('act_id', $act_id);
            }
            if ($unit_id) {
                $query->whereIn('unit_id', $unit_id);
            }
            if ($start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time, $end_time]);
            }
        })
            ->orderBy('dates')
            ->groupBy('dates')
            ->get()
            ->toArray();

        return $res;
    }
}
